package com.example.snakegame

import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.example.snakegame.databinding.ActivityLoginBinding
import com.example.snakegame.model.User
import com.example.snakegame.utils.SharedPreferencesManager

class LoginActivity : AppCompatActivity() {
    private lateinit var binding: ActivityLoginBinding
    private lateinit var prefsManager: SharedPreferencesManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_login)
        
        prefsManager = SharedPreferencesManager(this)

        binding.loginButton.setOnClickListener {
            val username = binding.usernameInput.text.toString()
            val password = binding.passwordInput.text.toString()

            if (username.isBlank() || password.isBlank()) {
                Toast.makeText(this, "请输入用户名和密码", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            val user = prefsManager.getUser(username)
            if (user == null) {
                // 新用户注册
                val newUser = User(username, password)
                prefsManager.saveUser(newUser)
                startGame(newUser)
            } else if (user.password == password) {
                // 登录成功
                startGame(user)
            } else {
                Toast.makeText(this, "密码错误", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun startGame(user: User) {
        val intent = Intent(this, GameActivity::class.java).apply {
            putExtra("username", user.username)
        }
        startActivity(intent)
        finish()
    }
} 